(function() {
'use strict';

angular
	.module('votingBackend')
	.controller('ResultsController', ['$scope', '$rootScope', '$state', '$http', '$sailsSocket', '$location', '$cookies', '$timeout', 'toastr', 'userDataService', 'AUTH_EVENTS', 'AuthService', 'localStorageService', ResultsController]);

	function ResultsController ($scope, $rootScope, $state, $http, $sailsSocket, $location, $cookies, $timeout, toastr, userDataService, AUTH_EVENTS, AuthService, localStorageService) {

	var _init = function(){
		$scope.activeQuiz = localStorageService.get('activeQuiz');
		$scope.activeQuizQr = localStorageService.get('activeQuizQr');
		$scope.activeVote = localStorageService.get('voteId');
		
		getAllUserData();

		//console.log($scope.activeVote);
	}

	_init();

	// var baseUrl = 'http://115.29.194.90:1234/'
	var baseUrl = 'http://localhost:1235/'

	//modify this to get active user data from local storage and remove hacky timeout on getAllResponse function
	function getAllUserData(){
		userDataService.provideAllUserData($scope.currentUser).then(function () {
			$scope.userData = userDataService.userData;
			$scope.userName = $scope.userData.name;
			$scope.userQuizzes = $scope.userData.quizzes;

            //iterate over user data and get all data for currently active quiz
            for (var i = 0; i < $scope.userData.quizzes.length; i++){
				if ($scope.userData.quizzes[i].id == $scope.activeQuiz.id) {
					$scope.activeQuizDeep = $scope.userData.quizzes[i];
					console.log($scope.activeQuizDeep)
				}
			}

			$timeout(function(){getAllResponses()},2000);
			$timeout(function(){getAllResponsesAlt()},2050);

			$timeout(function(){$scope.activeQuestion= $scope.activeQuizDeep.questions[$scope.activeQuestionIndex];
			console.log($scope.activeQuestion)}, 3000)
		})
	}


	// socket implementation
	function getAllResponses(){
		$sailsSocket.get(baseUrl + 'vote/' + $scope.activeVote)
		.then(function(res){
			$scope.responses = res.data.responses;
			buildAnswerDataStructure();
			//subcribe to vote object
		}, function(err){
			console.log('Error initializing socket connection to vote.')
			console.log(err)
		})
	}

	
	function getAllResponsesAlt(){
		$sailsSocket.get(baseUrl + 'response')
		.then(function(res){
			$sailsSocket.subscribe('response', function(msg){
				modifyAnswerDataStructure(msg.data.question_id, msg.data.answer_id);
			})
		}, function(err){
			console.log('Error initializing socket connection to response')
			console.log(err)
		})
	}
	

	//http implementation
	/*
	function getAllResponses(){
		$http.get('http://localhost:1234/vote/'+$scope.activeVote)
		.then(function (data){
			$scope.responses = data.data.responses;
			buildAnswerDataStructure();
		}, function (err){
			console.log('there has been an error retrieving responses');
			console.log(err);
		})
	}
	*/

	$scope.getHeight = function(answerIndex){
		var totalResponse = 0;
		for (var i = 0; i < $scope.activeQuestion.answers.length; i++){
			//get id from each answer of currently active question
			//add value to total response value
			totalResponse = totalResponse + $scope.allAnswersWithResponseCount[$scope.activeQuestion.answers[i].id]
		}
		var answerResponse = $scope.allAnswersWithResponseCount[$scope.activeQuestion.answers[answerIndex].id];
		var height = ((answerResponse/totalResponse) * 100) + '%'
		//console.log(height)
		return height 
	}

	$scope.letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

	$scope.activeQuestionIndex = 0;
	$scope.activeQuestion;

	function setActiveQuestion(){
		$scope.activeQuestion = $scope.activeQuizDeep.questions[$scope.activeQuestionIndex];
	}

	$scope.incrementActiveQuestionIndex = function(x){
		$scope.activeQuestionIndex = $scope.activeQuestionIndex + x;
		setActiveQuestion();
		//if (x == 1){
			$http.put('http://localhost:1235/vote/' + $scope.activeVote, {
				'activeQuestion': $scope.activeQuestion.id
			})
			.then(function(data){
				console.log('vote successfully updated')
				console.log(data)
			}, function(err){
				console.log('error updating activeQuestion of vote');
				console.log(err)
			})
		//}
	}

	function modifyAnswerDataStructure(question_id, answer_id){
		$scope.allAnswersWithResponseCount[answer_id] += 1;
	}

	function buildAnswerDataStructure(){
		$scope.allAnswersWithResponseCount = {};
		for (var i = 0; i < $scope.activeQuizDeep.questions.length; i++){
			//console.log($scope.activeQuizDeep.questions[i].answers);
			for (var j = 0; j < $scope.activeQuizDeep.questions[i].answers.length; j++){
				//console.log($scope.activeQuizDeep.questions[i].answers)
				$scope.allAnswersWithResponseCount[$scope.activeQuizDeep.questions[i].answers[j].id] = 0;
			}
		}
		//assign values from responses to new data structure with count for each response
		for (var k = 0; k < $scope.responses.length; k++){
			$scope.allAnswersWithResponseCount[$scope.responses[k].answer_id] += 1;
		}
		
		console.log('all answers with response count');
		console.log($scope.allAnswersWithResponseCount);
	}



	//console.log('logging the active quiz in the results controller')
	//console.log($scope.activeQuiz)
	//console.log($scope.activeQuizQr)
}
	
})();